#
# Modificacion del ejemplo http://matplotlib.org/examples/animation/animate_decay.html
#
# Requiere matplotlib

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# CONFIG
XLIMITS = (0, 5)
YLIMITS = (-1.1, 1.1)
CONTINUO = False
INTERVAL_UPDATE = 10


#Dummy generator of data. Replace it with the reading operation from USB
def data_gen():
   t = data_gen.t
   cnt = 0
   while cnt < 1000:
      cnt+=1
      t += 0.05
      yield t, np.sin(2*np.pi*t) * np.exp(-t/10.) # t, y
data_gen.t = 0

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([], [], lw=2)
ax.set_ylim(*YLIMITS)

XDELTA = XLIMITS[1] - XLIMITS[0]
ax.set_xlim(*XLIMITS)
ax.grid()
xdata, ydata = [], []
def run(data):
   # update the data (recieved from the frame_generator 'data_gen'
   t,y = data 
   xdata.append(t)
   ydata.append(y)
   xmin, xmax = ax.get_xlim()

   if t >= xmax:
      if CONTINUO:
         del xdata[:-1] # delete all except the new one. 'start again'
         del ydata[:-1]
         ax.set_xlim(int(xdata[0]), int(xdata[0])+XDELTA) #''move'' the window to the right (axe x)
         ax.figure.canvas.draw()
      else:
         del xdata[0] # delete the first value, xdata works like a queue
         del ydata[0]
         ax.set_xlim(xdata[0], t) #''move'' the window to the right (axe x) smooth


   line.set_data(xdata, ydata)

   return line,

ani = animation.FuncAnimation(fig, run, frames=data_gen, blit=True, interval=INTERVAL_UPDATE, repeat=False)
plt.show()
